import {Button, Checkbox, Form, Input, message} from 'antd';
import React from 'react';
import {Link, useNavigate} from 'react-router-dom'
import {login} from '@/services/user/api';
import '@/css/workflow.less'
import './index.less';
import {setAccessToken2LocalStorage, setLocalStorage, setUserInfo2LocalStorage} from "@/utils/localtion";
import {IUserInfo} from "@/redux/user/states";
import {ValidateErrorEntity} from "rc-field-form/lib/interface";
import * as states from "@/redux/states";
import userAction from "@/redux/user/actions";
import {connect} from "react-redux";
import store from "@/redux";

type FieldType = {
    username?: string;
    password?: string;
    remember?: string;
};

interface IErrorInfo extends ValidateErrorEntity{}


const LoginUI: React.FC = (props) => {
    // const [userLoginState, setUserLoginState] = useState<any>({});
    const navigate = useNavigate()

    const onFinishFailed = (errorInfo: IErrorInfo) => {
        console.log('Failed:', errorInfo);
    };


    // 存储用户信息
    const storeUserInfo = async (userInfo: IUserInfo) => {
        // 获取用户信息 用户角色, 用户权限,用户的消息等
        // 初始化用户信息, 将用户信息保存到redux中
        // currentUser: userInfo,

        if (userInfo) {
            setUserInfo2LocalStorage(userInfo);
            setAccessToken2LocalStorage(userInfo?.accessToken|| '')

            // TODO 开启轮询,每隔一分钟获取请求服务器,获取最新审批进度
        }
    };

    function setUserLoginState(userInfo: IUserInfo) {
        store.dispatch(userAction.SET_USER_INFO(userInfo))
    }

    const handleSubmit = async (values: API.LoginParams) => {
        try {
            // 登录
            const msg = await login({...values});
            // TODO 根据状态码判断是否成功,需要后端全局设置状态码, 现在用id和username判断一下
            if (Object.keys(msg).includes("username")&&Object.keys(msg).includes("id")) {
                const defaultLoginSuccessMessage = "登录成功";
                message.success(defaultLoginSuccessMessage);
                // 保存用户数据到本地浏览器
                setLocalStorage("userInfo", msg)

                setUserLoginState(msg);
                // 设置用户数据
                await storeUserInfo(msg);
                /** 此方法会跳转到 redirect 参数所在的位置, 长期未登录,重新登录回到原来的位置 */
                // TODO 获取历史记录,并返回最后操作页面
                navigate("/")
                return;
            }
            console.log(msg);
            // 如果失败去设置用户错误信息
            // setUserLoginState(msg);
        } catch (error) {
            const defaultLoginFailureMessage = "登录失败，请重试"
            message.error(defaultLoginFailureMessage);
        }
    };
    const onFinish = async (values: any) => {
        await handleSubmit(values as API.LoginParams);
    }

    return (<div className="container flex-center">

            <div className="row-flex-container">

                <Form
                    name="basic"
                    labelCol={{span: 8}}
                    wrapperCol={{span: 16}}
                    style={{maxWidth: 600}}
                    initialValues={{remember: true}}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                    autoComplete="off"
                >
                    <Form.Item<FieldType>
                        label="用户名"
                        name="username"
                        rules={[{required: true, message: '请输入用户名'}]}
                    >
                        <Input/>
                    </Form.Item>

                    <Form.Item<FieldType>
                        label="密码"
                        name="password"
                        rules={[{required: true, message: '请输入密码'}]}
                    >
                        <Input.Password/>
                    </Form.Item>

                    <Form.Item<FieldType>
                        name="remember"
                        valuePropName="checked"
                        wrapperCol={{offset: 8, span: 16}}
                    >
                        <Checkbox>记住我</Checkbox>
                    </Form.Item>

                    <Form.Item wrapperCol={{offset: 8, span: 16}}>
                        <Button type="primary" htmlType="submit">
                            登录
                        </Button>
                    </Form.Item>
                </Form>
                <p className="register">
                    <Link to='/register'>注册用户&gt;</Link>
                </p>
            </div>
        </div>
    );
}

const mapState = (state = states) => ({...state})

const mapDispatch = (action = userAction) => ({...action})
// TODO 只支持单页快更改
const Login= connect(
    mapState,
    mapDispatch
)(LoginUI)


export default Login;
